package dao.impl;

import dao.BaseDao;
import dao.CommodityClassDao;
import entity.CommodityClass;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class CommodityClassDaoImpl extends BaseDao implements CommodityClassDao {

    @Override
    public List<CommodityClass> findAllCalss() {
        String sql = "SELECT * FROM commodity_class";
        List<CommodityClass> list = new ArrayList<>();
        ResultSet rs = executeQuery(sql);
        try {
            while (rs.next()){
                CommodityClass commodityClass = new CommodityClass();
                commodityClass.setId(rs.getInt(1));
                commodityClass.setClassName(rs.getString(2));
                list.add(commodityClass);
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
        return list;
    }

    @Override
    public CommodityClass findId(int id) {
        String sql = "SELECT * FROM commodity_class WHERE id = ?";
        ResultSet rs = executeQuery(sql,id);
        try {
            if(rs.next()){
                CommodityClass commodityClass = new CommodityClass();
                commodityClass.setId(rs.getInt(1));
                commodityClass.setClassName(rs.getString(2));
                return commodityClass;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return null;
    }

    @Override
    public int add(String classNmae) {
        String sql = "INSERT INTO commodity_class(class_name) VALUES (?)";
        return executeUpdate(sql,classNmae);
    }

    @Override
    public int update(int id,String name) {
        String sql = "UPDATE commodity_class SET class_name=? WHERE id = ?";
        return executeUpdate(sql,name,id);
    }

    @Override
    public int delId(int id) {
        String sql = "DELETE FROM commodity_class WHERE id = ?";
        return executeUpdate(sql,id);
    }
}
